package leetcode.easy;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: $242_Anagram
 * Description:
 * date: 2021-09-30 14:22
 *
 * @author liyifan
 */
public class $242_Anagram {
    public boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) {
            return false;
        }
        HashMap<Character, Integer> map_s = new HashMap<>();
        HashMap<Character, Integer> map_t = new HashMap<>();

        for(Character c:s.toCharArray()) {
            map_s.put(c, map_s.getOrDefault(c, 0) + 1);
        }
        for (Character c:t.toCharArray()) {
            map_t.put(c, map_t.getOrDefault(c, 0) + 1);
        }
        if (map_s.size() != map_t.size())
            return false;

        for (Map.Entry e:map_s.entrySet()) {
            Character key = (Character) e.getKey();
            int val = (Integer) e.getValue();
            if (map_t.containsKey(key) && map_t.get(key) == val){
                continue;
            } else {
                return false;
            }
        }
        return true;
    }

    public boolean isAnagram2(String s, String t) {
        if (s.length() != t.length()) {
            return false;
        }
        char[] arr_s = s.toCharArray();
        char[] arr_t = t.toCharArray();
        Arrays.sort(arr_s);
        Arrays.sort(arr_t);
        String s_t = new String(arr_s);
        String t_t = new String(arr_t);
        return s_t.equals(t_t);
    }

    public boolean isAnagram3(String s, String t) {
        if (s.length() != t.length()) {
            return false;
        }
        int[] alpha = new int[26];

        for (int i = 0;i < s.length();i++) {
            alpha[s.charAt(i) - 'a']++;
            alpha[t.charAt(i) - 'a']--;
        }
        for (int i = 0;i < 26;i++) {
            if (alpha[i] != 0)
                return false;
        }
        return true;
    }
}
